/*
 * hik video show tiny http server
 */

#include "hv/hv.h"
#include "hv/hloop.h"
#include "hv/httpdef.h"

#define CONTENT_TYPE_STR_TEXT_HTML "text/html; charset=utf-8"

#define MOUNT_HTML_DIR  "../webs"
static char listen_host[64] = "0.0.0.0";
static int  listen_port = 8888;
static int  listen_ssl = 0;

static int thread_num = 1;
static hloop_t*  accept_loop = NULL;
static hloop_t** worker_loops = NULL;

#define HTTP_KEEPALIVE_TIMEOUT  60000 // ms
#define HTTP_MAX_URL_LENGTH     256
#define HTTP_MAX_HEAD_LENGTH    4096

#define HTML_TAG_BEGIN  "<html><body><center><h1>"
#define HTML_TAG_END    "</h1></center></body></html>"

// status_message
#define HTTP_OK         "OK"
#define NOT_FOUND       "Not Found"
#define NOT_IMPLEMENTED "Not Implemented"




typedef struct _target_msg_t{
    void*       next;
    char        target_firstline[256];
    char        target_firstline_len;
    char        target_head[HTTP_MAX_HEAD_LENGTH];
    int         target_head_len;
} target_msg_t;

typedef enum {
    s_begin,
    s_first_line,
    s_request_line = s_first_line,
    s_status_line = s_first_line,
    s_head,
    s_head_end,
    s_body,
    s_end
} http_state_e;

typedef struct {
    // first line
    int             major_version;
    int             minor_version;
    union {
        // request line
        struct {
            char method[32];
            char path[HTTP_MAX_URL_LENGTH];
        };
        // status line
        struct {
            int  status_code;
            char status_message[64];
        };
    };
    // headers
    char        host[64];
    int         content_length;
    char        content_type[64];
    unsigned    keepalive:  1;
    
    // body
    char*       body;
    int         body_len; // body_len = content_length

} http_msg_t;

typedef struct {
    hio_t*          io;
    http_state_e    state;
    http_msg_t      request;
    http_msg_t      response;
     // for http_serve_file
    FILE*           fp;
    hbuf_t          filebuf;
    // proxy
    unsigned    proxy:      2;
    unsigned    target_connected:      1;
    target_msg_t *target_msg;
    char        target_host[64];
    int         target_port;
    char        target_host2[64];
    int         target_port2;
    char        target_channel[64];
} http_conn_t;


static char s_date[32] = {0};
static void update_date(htimer_t* timer) {
    uint64_t now = hloop_now(hevent_loop(timer));
    gmtime_fmt(now, s_date);
}
static int http_response_dump(http_msg_t* msg, char* buf, int len) {
    int offset = 0;
    // status line
    offset += snprintf(buf + offset, len - offset, "HTTP/%d.%d %d %s\r\n", msg->major_version, msg->minor_version, msg->status_code, msg->status_message);
    // headers
    offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version());
    offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close");
    if (msg->content_length > 0) {
        offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length);
    }
    if (*msg->content_type) {
        offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type);
    }
    if (*s_date) {
        offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date);
    }
    // TODO: Add your headers
    offset += snprintf(buf + offset, len - offset, "\r\n");
    // body
    if (msg->body && msg->body_len > 0) {
        memcpy(buf + offset, msg->body, msg->body_len);
        offset += msg->body_len;
    }
    return offset;
}

static int http_reply(http_conn_t* conn,
            int status_code, const char* status_message,
            const char* content_type,
            const char* body, int body_len) {
    http_msg_t* req  = &conn->request;
    http_msg_t* resp = &conn->response;
    resp->major_version = req->major_version;
    resp->minor_version = req->minor_version;
    resp->status_code = status_code;
    if (status_message) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1);
    if (content_type)   strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1);
    resp->keepalive = req->keepalive;
    if (body) {
        if (body_len <= 0) body_len = strlen(body);
        resp->content_length = body_len;
        resp->body = (char*)body;
    } else {
        resp->content_length = 0;
        resp->body = NULL;
        resp->body_len = 0;
    }
    char* buf = NULL;
    STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024);
    int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length);
    int nwrite = hio_write(conn->io, buf, msglen);
    STACK_OR_HEAP_FREE(buf);
    return nwrite < 0 ? nwrite : msglen;
}

static void http_send_file(http_conn_t* conn) {
    if (!conn || !conn->fp) return;
    // alloc filebuf
    if (!conn->filebuf.base) {
        conn->filebuf.len = 4096;
        HV_ALLOC(conn->filebuf, conn->filebuf.len);
    }
    char* filebuf = conn->filebuf.base;
    size_t filebuflen = conn->filebuf.len;
    // read file
    int nread = fread(filebuf, 1, filebuflen, conn->fp);
    if (nread <= 0) {
        // eof or error
        hio_close(conn->io);
        printf("conn=%p %s fread end.\n", conn, __func__);
        return;
    }
    // send file
    hio_write(conn->io, filebuf, nread);
}

static void on_write(hio_t* io, const void* buf, int writebytes) {
    if (!io) return;
    if (!hio_write_is_complete(io)) return;
    http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
    http_send_file(conn);
}

static int http_serve_file(http_conn_t* conn) {
    http_msg_t* req = &conn->request;
    http_msg_t* resp = &conn->response;
    char filepath[PATH_MAX] = {0};
    char *p = NULL;
    // GET / HTTP/1.1\r\n
    // homepage
    if (*(req->path+1) == '\0') {
        snprintf(filepath, sizeof(filepath), "%s%sindex.html", MOUNT_HTML_DIR, req->path );
    }else {
        snprintf(filepath, sizeof(filepath), "%s%s", MOUNT_HTML_DIR, req->path );
    }
    if((p=strchr(filepath, '?')) != NULL) {
        *p='\0';
    }
    // open file
    conn->fp = fopen(filepath, "rb");
    if (!conn->fp) {
        http_reply(conn, 404, NOT_FOUND, CONTENT_TYPE_STR_TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0);
        return 404;
    }
    // send head
    size_t filesize = hv_filesize(filepath);
    resp->content_length = filesize;
    const char* suffix = hv_suffixname(filepath);
    const char* content_type = NULL;
    http_content_type content_type_enum = http_content_type_enum_by_suffix(suffix);
    if (content_type_enum == TEXT_HTML) {
        content_type = "text/html; charset=utf-8";
    } else if (content_type_enum == TEXT_PLAIN) {
        content_type = "text/plain; charset=utf-8";
    } else {
        content_type = http_content_type_str_by_suffix(suffix);
    }
    hio_setcb_write(conn->io, on_write);
    int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0);
    if (nwrite < 0) return nwrite; // disconnected
    return 200;
}

static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) {
    // GET / HTTP/1.1
    http_msg_t* req = &conn->request;
    sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version);
    if (req->major_version != 1) return false;
    if (req->minor_version == 1) req->keepalive = 1;
    // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version);
    return true;
}

static bool parse_http_head(http_conn_t* conn, char* buf, int len) {
    http_msg_t* req = &conn->request;
    // Content-Type: text/html
    const char* key = buf;
    const char* val = buf;
    const char *p =NULL,*p1 =NULL,*p2 = NULL, *p3=NULL;
    char tmp[1024] = {0};
    char* delim = strchr(buf, ':');
    if (!delim) return false;
    *delim = '\0';
    val = delim + 1;
    // trim space
    while (*val == ' ') ++val;
    // printf("%s: %s\r\n", key, val);
    if (stricmp(key, "Host") == 0) {
        strncpy(req->host, val, sizeof(req->host) - 1);
    } else if (stricmp(key, "Content-Length") == 0) {
        req->content_length = atoi(val);
    } else if (stricmp(key, "Content-Type") == 0) {
        strncpy(req->content_type, val, sizeof(req->content_type) - 1);
    } else if (stricmp(key, "Connection") == 0 || stricmp(key, "Proxy-Connection") == 0) {
        if (stricmp(val, "close") == 0) {
            req->keepalive = 0;
        }
    } else if (stricmp(key, "Cookie") == 0) {
        p = val;
        while (p) {
            p1 = strstr(p, "; ");
            memset(tmp, 0, sizeof(tmp));
            if (p1) {
                memcpy(tmp, p, p1 - p);
                p = p1 + 2;
            } else {
                strcpy(tmp, p);
                p = NULL;
            }
            // printf("cookie %s\n", tmp);
            if ((p2 = strstr(tmp, "webVideoCtrlProxy=")) != NULL) {
                p2 += strlen("webVideoCtrlProxy=");
                p3 = strstr(p2, ":");
                memset(conn->target_host, 0, sizeof(conn->target_host));
                strncpy(conn->target_host, p2, p3 - p2);
                conn->target_port = atoi(p3+1);
                printf("conn->target_host=%s conn->target_port=%d\n", conn->target_host, conn->target_port);
            } else if ((p2 = strstr(tmp, "webVideoCtrlProxyWs=")) != NULL) {
                p2 += strlen("webVideoCtrlProxyWs=");
                p3 = strstr(p2, ":");
                memset(conn->target_host2, 0, sizeof(conn->target_host2));
                strncpy(conn->target_host2, p2, p3 - p2);
                conn->target_port2 = atoi(p3+1);
                printf("conn->target_host2=%s conn->target_port2=%d\n", conn->target_host2, conn->target_port2);
            } else if ((p2 = strstr(tmp, "webVideoCtrlProxyWsChannel=")) != NULL) {
                p2 += strlen("webVideoCtrlProxyWsChannel=");
                strcpy(conn->target_channel, p2);
                printf("conn->target_channel=%s\n", conn->target_channel);
            }
        }
    }
    // printf("conn=%p %s %s\n",conn,__func__, buf);
    return true;
}

static void on_upstream_connect(hio_t* upstream_io) {
    printf("on_upstream_connect\n");
    http_conn_t* conn = (http_conn_t*)hevent_userdata(upstream_io);
    http_msg_t* req = &conn->request;
    conn->target_connected = 1;
    // send head
    target_msg_t *msg = conn->target_msg, *next = NULL;
    char stackbuf[HTTP_MAX_HEAD_LENGTH + 1024] = {0};
    char* buf = stackbuf;
    int len = sizeof(stackbuf);
    int  offset = 0;
    char peeraddrstr[SOCKADDR_STRLEN] = {0};
    char *p = NULL;
    // char tmp[256] = { 0x00 };
    char method[32] = { 0x00 };
    char path[256] = { 0x00 };
    int major_version;
    int minor_version;
    while (msg) {
        offset = 0;
        if (conn->proxy == 1) {
            offset += snprintf(buf+offset, len - offset, "%s", msg->target_firstline);
        } else {
            sscanf(msg->target_firstline, "%s %s HTTP/%d.%d", method, path, &major_version, &minor_version);
            p = strstr(path, "?");
            if (p) {
                *p = '\0';
            } else {
                p=path;
            }
            offset += snprintf(buf + offset, len - offset, "%s /%s?%s HTTP/%d.%d\r\n", method, conn->target_channel,p+1, 
                major_version, minor_version);
            offset += snprintf(buf + offset, len - offset, "Upgrade: websocket\r\n");
        }
        offset += snprintf(buf + offset, len - offset, "Connection: upgrade\r\n");
        memset(peeraddrstr, 0x00, sizeof(peeraddrstr));
        SOCKADDR_STR(hio_peeraddr(upstream_io), peeraddrstr);
        if ((p = strstr(peeraddrstr, ":")) != NULL) {
            *p='\0';
        }
        offset += snprintf(buf + offset, len - offset, "Host: %s\r\n", peeraddrstr);
        if (conn->proxy == 1) {
            memset(peeraddrstr, 0x00, sizeof(peeraddrstr));
            SOCKADDR_STR(hio_peeraddr(conn->io), peeraddrstr);
            if ((p = strstr(peeraddrstr, ":")) != NULL) {
                *p='\0';
            }
            offset += snprintf(buf + offset, len - offset, "X-real-ip: %s\r\n", peeraddrstr);
            offset += snprintf(buf + offset, len - offset, "X-Origin-IP: %s\r\n", peeraddrstr);
            offset += snprintf(buf + offset, len - offset, "X-Forwarded-For: %s\r\n", peeraddrstr);
        }
        offset += snprintf(buf + offset, len - offset, "%s", msg->target_head);
        hio_write(upstream_io, buf, offset);
        next = (target_msg_t *)msg->next;
        free(msg);
        msg = next;
        printf("conn=%p on_upstream_connect hio_write req->proxy=%d len=%d buf=%s\n",
            conn, conn->proxy, offset, buf);
    }
    conn->target_msg = NULL;
    if (conn->state != s_end || conn->proxy == 2) {
        // start recv body then upstream
        hio_read_start(conn->io);
    } else {
        if (req->keepalive) {
            // Connection: keep-alive\r\n
            // reset and receive next request
            memset(&conn->request,  0, sizeof(http_msg_t));
            // memset(&conn->response, 0, sizeof(http_msg_t));
            conn->state = s_first_line;
            hio_readline(conn->io);
        }
    }
    // start recv response
    int ret = hio_read_start(upstream_io);
    printf("conn=%p %s call hio_read_start after proxy=%d ret=%d\n",
            conn,__func__, conn->proxy, ret);
}

static int on_head_end(http_conn_t* conn) {
    int ret = 0;
    http_msg_t* req = &conn->request;
    if (req->host[0] == '\0') {
        fprintf(stderr, "No Host header!\n");
        return -1;
    }
    printf("conn=%p on_head_end req->path=%s %s:%d %s:%d\n", conn, req->path
        , conn->target_host, conn->target_port
        , conn->target_host2, conn->target_port2
    );
    char *host = NULL;
    int   port = 0;
    if (strstr(req->path, "/ISAPI/") == req->path  &&  strlen(conn->target_host) > 2 &&  conn->target_port > 0) {
        host = conn->target_host;
        port = conn->target_port;
        conn->proxy = 1;
    } 
    else if (strstr(req->path, "/SDK/") == req->path  &&  strlen(conn->target_host) > 2 &&  conn->target_port > 0) {
        host = conn->target_host;
        port = conn->target_port;
        conn->proxy = 1;
    }
    else if (strstr(req->path, "/webSocketVideoCtrlProxy")   &&  
        strlen(conn->target_host2) > 2 &&  conn->target_port2 > 0) {
        host = conn->target_host2;
        port = conn->target_port2;
        conn->proxy = 2;
    }
    else {
        conn->proxy = 0;
        return 0;
    }
    // NOTE: blew for proxy
    
    // int backend_ssl = strncmp(req->path, "https", 5) == 0 ? 1 : 0;
    printf("%s upstream path=%s %s:%d\n",__func__, req->path, host, port);
    hloop_t* loop = hevent_loop(conn->io);
    // hio_t* upstream_io = hio_setup_tcp_upstream(conn->io, backend_host, backend_port, backend_ssl);
    hio_t* upstream_io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
    if (upstream_io == NULL) {
        fprintf(stderr, "Failed to upstream %s:%d!\n", host, port);
        return -3;
    }
    // if (backend_ssl) {
    //     hio_enable_ssl(upstream_io);
    // }
    hevent_set_userdata(upstream_io, conn);
    hio_setup_upstream(conn->io, upstream_io);
    hio_setcb_read(upstream_io, hio_write_upstream);
    hio_setcb_close(upstream_io, hio_close_upstream);
    hio_setcb_connect(upstream_io, on_upstream_connect);
    ret = hio_connect(upstream_io);
    printf("conn=%p upstream=%p %s hio_connect ret=%d path=%s %s:%d\n",conn, upstream_io, __func__, ret, 
            req->path, host, port
    );
    return 0;
}

static int on_body(http_conn_t* conn, void* buf, int readbytes) {
    if (conn->proxy) {
        hio_write_upstream(conn->io, buf, readbytes);
    }
    return 0;
}

static int on_request(http_conn_t* conn) {
    // NOTE: just reply 403, please refer to examples/tinyhttpd if you want to reply other.
    http_msg_t* req = &conn->request;

    if (strcmp(req->method, "GET") == 0) {
        return http_serve_file(conn);
    }

    char buf[256] = {0};
    int len = snprintf(buf, sizeof(buf), "HTTP/%d.%d %d %s\r\nContent-Length: 0\r\n\r\n",
            req->major_version, req->minor_version, 403, "Forbidden");
    hio_write(conn->io, buf, len);
    return 403;
}

static void on_close(hio_t* io) {
    // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
    http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
    printf("conn=%p io=%p %s proxy=%d\n", conn, io, __func__, conn->proxy);
    if (conn) {
        if (conn->fp) {
            // close file
            fclose(conn->fp);
            conn->fp = NULL;
        }
        // free filebuf
        HV_FREE(conn->filebuf.base);
        target_msg_t *msg,*next;
        msg = conn->target_msg;
        while (msg) {
            next = (target_msg_t *)msg->next;
            free(msg);
            msg = next;
        }
        conn->target_msg = NULL;
        HV_FREE(conn);
        hevent_set_userdata(io, NULL);
    }
    hio_close_upstream(io);
    
}

static void on_recv(hio_t* io, void* buf, int readbytes) {
    char* str = (char*)buf;
    // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
    // printf("%.*s", readbytes, str);
    http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
    http_msg_t* req = &conn->request;
    target_msg_t *msg = conn->target_msg, *new_msg;
    while(msg && msg->next) {
        msg = (target_msg_t *)msg->next;
    }
    switch (conn->state) {
    case s_begin:
        // printf("s_begin");
        conn->state = s_first_line;
    case s_first_line:
        new_msg = (target_msg_t *)malloc(sizeof(target_msg_t));
        memset(new_msg, 0, sizeof(target_msg_t));
        if (conn->target_msg) {
            msg->next = new_msg;
        } else {
            conn->target_msg = new_msg;
        }
        msg = new_msg;
        // printf("conn=%p io=%p %s state=%d readbytes=%d buf=%s\n",conn, io,__func__, conn->state, readbytes, (char *)buf);
        // printf("s_first_line\n");
        if (readbytes < 2) {
            fprintf(stderr, "Not match \r\n!");
            hio_close(io);
            return;
        }
        if (conn->target_connected) {
            hio_write_upstream(io, buf, readbytes);
        } else {
            memcpy(msg->target_firstline, buf, readbytes);
            msg->target_firstline_len = readbytes;
        }
        str[readbytes - 2] = '\0';
        if (parse_http_request_line(conn, str, readbytes - 2) == false) {
            fprintf(stderr, "Failed to parse http request line:\n%s\n", str);
            hio_close(io);
            return;
        }
        // start read head
        conn->state = s_head;
        hio_readline(io);
        break;
    case s_head:
        // printf("conn=%p %s state=%d readbytes=%d buf=%s\n",conn,__func__, conn->state, readbytes, (char *)buf);
        // printf("s_head\n");
        if (readbytes < 2) {
            fprintf(stderr, "Not match \r\n!");
            hio_close(io);
            return;
        }
        if (conn->target_connected) {
            hio_write_upstream(io, buf, readbytes);
        } else {
            if (strstr(str, "Host:") != str && 
                strstr(str, "Connection:") != str &&
                strstr(str, "Upgrade:") != str 
            ) {
                if (msg->target_head_len + readbytes < HTTP_MAX_HEAD_LENGTH) {
                    memcpy(msg->target_head + msg->target_head_len, buf, readbytes);
                    msg->target_head_len += readbytes;
                }
            }
        }
        if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') {
            conn->state = s_head_end;
        } else {
            str[readbytes - 2] = '\0';
            if (parse_http_head(conn, str, readbytes - 2) == false) {
                fprintf(stderr, "Failed to parse http head:\n%s\n", str);
                hio_close(io);
                return;
            }
            hio_readline(io);
            break;
        }
    case s_head_end:
        printf("conn=%p %s state=%d s_head_end readbytes=%d buf=%s\n",conn,__func__, conn->state, readbytes, (char *)buf);
        // printf("s_head_end\n");
        if (on_head_end(conn) < 0) {
            hio_close(io);
            printf("conn=%p %s on_head_end end state=%d s_head_end readbytes=%d buf=%s\n",conn,__func__, conn->state, readbytes, (char *)buf);
            return;
        }
        if (req->content_length == 0 && conn->proxy == 0) {
            conn->state = s_end;
            goto s_end;
        } else {
            conn->state = s_body;
            if (conn->proxy) {
                // NOTE: start read body on_upstream_connect
                // hio_read_start(io);
            } else {
                // WARN: too large content_length should read multiple times!
                hio_readbytes(io, req->content_length);
            }
            break;
        }
    case s_body:
        printf("conn=%p io=%p %s state=%d s_body is_proxy=%d readbytes=%d buf=%s req->content_length=%d\n",
            conn,io, __func__, conn->state, conn->proxy, readbytes, (char *)buf, req->content_length);
        // printf("s_body\n");
        if (on_body(conn, buf, readbytes) < 0) {
            printf("conn=%p %s on_body end state=%d readbytes=%d buf=%s\n",conn,__func__, conn->state, readbytes, (char *)buf);
            hio_close(io);
            return;
        }
        if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') {
            conn->state = s_end;
        } else {
            req->body = str;
            req->body_len += readbytes;
        }
        // if (req->body_len == req->content_length) {
        //     conn->state = s_end;
        // } else {
        //     // Not end
        //     break;
        // }
    case s_end:
s_end:
        printf("conn=%p io=%p %s state=%d s_end is_proxy=%d readbytes=%d buf=%s\n",
            conn, io,__func__, conn->state, conn->proxy, readbytes, (char *)buf);
        // printf("s_end\n");
        // received complete request
        if (conn->proxy) {
            // NOTE: reply by upstream
        } else {
            on_request(conn);
        }
        if (hio_is_closed(io)) return;
        if (req->keepalive) {
            // Connection: keep-alive\r\n
            // reset and receive next request
            memset(&conn->request,  0, sizeof(http_msg_t));
            // memset(&conn->response, 0, sizeof(http_msg_t));
            conn->state = s_first_line;
            hio_readline(io);
        } else {
            // Connection: close\r\n
            if (conn->proxy) {
                // NOTE: wait upstream close!
            } else {
                hio_close(io);
                printf("conn=%p io=%p %s hio_close state=%d is_proxy=%d readbytes=%d buf=%s\n",
                    conn, io,__func__, conn->state, conn->proxy, readbytes, (char *)buf);
            }
        }
        break;
    default: break;
    }
}

static void new_conn_event(hevent_t* ev) {
    hloop_t* loop = ev->loop;
    hio_t* io = (hio_t*)hevent_userdata(ev);
    hio_attach(loop, io);

    /*
    char localaddrstr[SOCKADDR_STRLEN] = {0};
    char peeraddrstr[SOCKADDR_STRLEN] = {0};
    printf("tid=%ld connfd=%d [%s] <= [%s]\n",
            (long)hv_gettid(),
            (int)hio_fd(io),
            SOCKADDR_STR(hio_localaddr(io), localaddrstr),
            SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
    */

    hio_setcb_close(io, on_close);
    hio_setcb_read(io, on_recv);
    hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT);

    http_conn_t* conn = NULL;
    HV_ALLOC_SIZEOF(conn);
    conn->io = io;
    hevent_set_userdata(io, conn);
    // start read first line
    conn->state = s_first_line;
    hio_readline(io);
}

static hloop_t* get_next_loop() {
    static int s_cur_index = 0;
    if (s_cur_index == thread_num) {
        s_cur_index = 0;
    }
    return worker_loops[s_cur_index++];
}

static void on_accept(hio_t* io) {
    hio_detach(io);

    hloop_t* worker_loop = get_next_loop();
    hevent_t ev;
    memset(&ev, 0, sizeof(ev));
    ev.loop = worker_loop;
    ev.cb = new_conn_event;
    ev.userdata = io;
    hloop_post_event(worker_loop, &ev);
}

static HTHREAD_ROUTINE(worker_thread) {
    hloop_t* loop = (hloop_t*)userdata;
    hloop_run(loop);
    return 0;
}

static HTHREAD_ROUTINE(accept_thread) {
    hloop_t* loop = (hloop_t*)userdata;
    hio_t* listenio = hloop_create_tcp_server(loop, listen_host, listen_port, on_accept);
    if (listenio == NULL) {
        exit(1);
    }
    if (listen_ssl) {
        hio_enable_ssl(listenio);
    }
    printf("tinyhttpd listening on %s:%d, listenfd=%d, thread_num=%d\n",
            listen_host, listen_port, hio_fd(listenio), thread_num);
    htimer_add(loop, update_date, 1000, INFINITE);
    hloop_run(loop);
    return 0;
}

int main(int argc, char** argv) {
    thread_num = get_ncpu();
    if (thread_num == 0) thread_num = 1;

    worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num);
    for (int i = 0; i < thread_num; ++i) {
        worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE);
        hthread_create(worker_thread, worker_loops[i]);
    }

    accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
    accept_thread(accept_loop);
    return 0;
}
